package org.jeecg.modules.online.graphreport.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.online.graphreport.entity.OnlGraphreportHead;
import org.jeecg.modules.online.graphreport.entity.OnlGraphreportItem;
import org.jeecg.modules.online.graphreport.entity.OnlGraphreportParams;
import org.jeecg.modules.online.graphreport.mapper.OnlGraphreportHeadMapper;
import org.jeecg.modules.online.graphreport.mapper.OnlGraphreportItemMapper;
import org.jeecg.modules.online.graphreport.mapper.OnlGraphreportParamsMapper;
import org.jeecg.modules.online.graphreport.service.IOnlGraphreportHeadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 图表报告
 * @Author:jeecg-boot
 * @Date: 2019-04-10
 * @Version:V1.0
 */
@Service("onlGraphreportHeadServiceImpl")
public class OnlGraphreportHeadServiceImpl extends ServiceImpl<OnlGraphreportHeadMapper, OnlGraphreportHead> implements IOnlGraphreportHeadService {

	@Autowired
	private OnlGraphreportHeadMapper onlGraphreportHeadMapper;
	@Autowired
	private OnlGraphreportItemMapper onlGraphreportItemMapper;
	@Autowired
	private OnlGraphreportParamsMapper onlGraphreportParamsMapper;

	@Autowired
	private ISysBaseAPI sysBaseAPI;

	/**
	 * 执行查询SQL语句
	 * 
	 * @param sql
	 * @return
	 */
	@Override
	public List<Map<String, Object>> executeSelete(String sql) {
		return onlGraphreportHeadMapper.executeSelete(sql);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(OnlGraphreportHead onlGraphreportHead, List<OnlGraphreportItem> onlGraphreportItemList, List<OnlGraphreportParams> paramsList) {
		if (onlGraphreportHead.getYaxisText() == null) {
			onlGraphreportHead.setYaxisText("yaxis_text");
		}
		onlGraphreportHeadMapper.insert(onlGraphreportHead);
		for (OnlGraphreportItem entity : onlGraphreportItemList) {
			// 外键设置
			entity.setGraphreportHeadId(onlGraphreportHead.getId());
			onlGraphreportItemMapper.insert(entity);
		}
		for (OnlGraphreportParams entity : paramsList) {
			// 外键设置
			entity.setHeadId(onlGraphreportHead.getId());
			onlGraphreportParamsMapper.insert(entity);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(OnlGraphreportHead onlGraphreportHead, List<OnlGraphreportItem> onlGraphreportItemList, List<OnlGraphreportParams> paramsList) {
		onlGraphreportHeadMapper.updateById(onlGraphreportHead);

		// 1.先删除子表数据
		onlGraphreportItemMapper.deleteByMainId(onlGraphreportHead.getId());
		onlGraphreportParamsMapper.deleteByMainId(onlGraphreportHead.getId());

		// 2.子表数据重新插入
		for (OnlGraphreportItem entity : onlGraphreportItemList) {
			// 外键设置
			entity.setGraphreportHeadId(onlGraphreportHead.getId());
			onlGraphreportItemMapper.insert(entity);
		}
		for (OnlGraphreportParams entity : paramsList) {
			// 外键设置
			entity.setHeadId(onlGraphreportHead.getId());
			onlGraphreportParamsMapper.insert(entity);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		onlGraphreportHeadMapper.deleteById(id);
		onlGraphreportItemMapper.deleteByMainId(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for (Serializable id : idList) {
			onlGraphreportHeadMapper.deleteById(id);
			onlGraphreportItemMapper.deleteByMainId(id.toString());
		}
	}

	@Override
	public OnlGraphreportHead queryByCode(String code) {
		QueryWrapper<OnlGraphreportHead> queryWrapper = new QueryWrapper<OnlGraphreportHead>();
		queryWrapper.eq("code", code);

		return this.getOne(queryWrapper);
	}


	@Override
	@Cacheable(value = CacheConstant.ONLINE_GRAPH, key = "#head.id")
	public Map<String, Object> queryChartConfig(OnlGraphreportHead head) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("head", head);
		//手工将字段都转为小写，为了兼容各种数据库
		if (head.getYaxisField() != null) {
			head.setYaxisField(head.getYaxisField().toLowerCase());
		}
		if (head.getXaxisField() != null) {
			head.setXaxisField(head.getXaxisField().toLowerCase());
		}

		// 根据headId查询出items
		List<OnlGraphreportItem> items = onlGraphreportItemMapper.selectByMainId(head.getId());
		//手工将字段都转为小写，为了兼容各种数据库
		for (OnlGraphreportItem i : items) {
			if (i.getFieldName() != null) {
				i.setFieldName(i.getFieldName().toLowerCase());
			}
		}

		// 字典 map
		Map<String, Object> dictOptions = new HashMap<>(0);

		for (OnlGraphreportItem item : items) {
			String dictCode = item.getDictCode();
			if (!StringUtils.isEmpty(dictCode)) {

				List<DictModel> dictList = null;
				// 判断字典是否是 select 开头的，如果是就认定为是一个 sql 语句，执行该语句获取数据并当做字典使用
				if (dictCode.toLowerCase().trim().indexOf("select ") == 0) {
					List<Map<String, Object>> queryDictList = this.executeSelete(dictCode);
					if (queryDictList != null && queryDictList.size() != 0) {
						// 通过 fastJson 转为 java DictModel对象
						String queryDictJson = JSON.toJSONString(queryDictList);
						dictList = JSON.parseArray(queryDictJson, DictModel.class);
					}
				} else {
					// 普通字典
					dictList = sysBaseAPI.queryDictItemsByCode(dictCode);
				}
				dictOptions.put(item.getFieldName(), dictList);
			}
		}

		resultMap.put("items", items);
		resultMap.put("dictOptions", dictOptions);
		return resultMap;
	}

}
